package com.dream.myqiyi.ui;

import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.Formatter;
import java.util.Locale;

import com.dream.myqiyi.Global;
import com.dream.myqiyi.R;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class RecorderActivity extends Activity implements OnClickListener {
	private MediaPlayer mediaPlayer;
	private MediaRecorder mediaRecorder = new MediaRecorder();
	private File audioFile;
	private long start = 0;
	private long end = 0;
	private long length = 0;
	private boolean recordMode = true;
	
	private TextView recordTimeTv;
	private SeekBar recordSeekBar;
	
	private Handler recordSeekBarHandler = new Handler();
	private Runnable refresh = new Runnable() {
		public void run() {
			int currently_Progress = recordSeekBar.getProgress() + 1000;	
			recordSeekBar.setProgress(currently_Progress);
			recordTimeTv.setText(getTime((new Date()).getTime() - start));
			recordSeekBarHandler.postDelayed(refresh, 1000);
		}
	};


	public void onClick(View view) {
		try {
			String msg = "";			
			switch (view.getId()) {
				case R.id.btnStart:
					mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
					mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
					mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
					audioFile = new File(getRecorderFileName());
					mediaRecorder.setOutputFile(audioFile.getAbsolutePath());
					mediaRecorder.prepare();
					mediaRecorder.start();
					start = (new Date()).getTime();
					msg = "正在录音...";	
					recordSeekBarHandler.postDelayed(refresh, 1000);
					setTitle(msg);
					Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
					break;
					
				case R.id.btnStop:
					if (recordMode) {
						if (audioFile != null) {
							mediaRecorder.stop();
							end = (new Date()).getTime();
							length = end - start; 
							
							Intent intent = new Intent(RecorderActivity.this, NoteViewActivity.class);
							Bundle newBundle = new Bundle();
							newBundle.putString("select_result", "record");
							newBundle.putString("sound_file", audioFile.getAbsolutePath());
							newBundle.putInt("sound_length", Integer.parseInt((Long.toString(length / 1000))));
							intent.putExtras(newBundle);
							RecorderActivity.this.setResult(NoteViewActivity.RECORDER_SELECTED_RESULT, intent);
							RecorderActivity.this.finish();						
						}
						msg = "已经停止录音.";							
						setTitle(msg);
						Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
					} else {
						
						Intent intent = new Intent(RecorderActivity.this, NoteViewActivity.class);
						RecorderActivity.this.setResult(NoteViewActivity.RECORDER_VIEW_RESULT, intent);
						RecorderActivity.this.finish();	
					}
					recordSeekBarHandler.removeCallbacks(refresh);
					break;
					
				case R.id.btnPlay:
					if (audioFile != null)  {		
						mediaPlayer = new MediaPlayer();
						@SuppressWarnings("resource")
						FileInputStream fis = new FileInputStream(audioFile); 
						mediaPlayer.setDataSource(fis.getFD());
						mediaPlayer.prepare();
						
						mediaPlayer.start();
						mediaPlayer.setOnCompletionListener(new OnCompletionListener() {							
							@Override
							public void onCompletion(MediaPlayer mp) {
								setTitle("录音播放完毕.");
							}
						});
						msg = "正在播放录音...";						
						setTitle(msg);
						Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
					}
					break;

			}
		}
		catch (Exception e)
		{
			setTitle(e.getMessage());
		}

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.recorder);
		Button btnStart = (Button) findViewById(R.id.btnStart);
		Button btnStop = (Button) findViewById(R.id.btnStop);
		Button btnPlay = (Button) findViewById(R.id.btnPlay);
		recordTimeTv = (TextView) findViewById(R.id.record_time);
		recordSeekBar = (SeekBar) findViewById(R.id.record_seekBar);
		recordSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {

			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
			}
		});

		recordMode = true;
		Bundle bundle = this.getIntent().getExtras();
		if (bundle != null) {
			String mode = bundle.getString("record_mode");
			if (mode != null && mode.equals("play")) { // 播放模式
				recordMode = false;
				String soundFile = bundle.getString("audio_file");
				audioFile = new File(soundFile);
				
				btnStart.setVisibility(View.GONE);
				btnPlay.setVisibility(View.VISIBLE);			
				btnPlay.setOnClickListener(this);
			} else { // 录音模式
				btnStart.setVisibility(View.VISIBLE);
				btnStart.setOnClickListener(this);
				btnPlay.setVisibility(View.GONE);
			}
		} else { // 录音模式
			btnStart.setVisibility(View.VISIBLE);
			btnStart.setOnClickListener(this);
			btnPlay.setVisibility(View.GONE);
		}
		
		btnStop.setOnClickListener(this);
	}
	
	private String getRecorderFileName() {
		return Global.resDir + Global.getGuid() + ".amr";
	}

	private String getTime(long timeMs) {
		long totalSeconds = timeMs / 1000;
		StringBuilder mFormatBuilder = new StringBuilder();
		@SuppressWarnings("resource")
		Formatter formatter = new Formatter(mFormatBuilder, Locale.getDefault());
		long seconds = totalSeconds % 60;
		long minutes = (totalSeconds / 60) % 60;
		long hours = totalSeconds / 3600;
		mFormatBuilder.setLength(0);

		if (hours > 0) {
			return formatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
		} else {
			return formatter.format("%02d:%02d", minutes, seconds).toString();
		}
	}

}
